import { computed, ref, onBeforeMount } from 'vue'
import { fetchMenuConfig, setMenu } from '../axioser'
import { ElMessage } from 'element-plus'

export function useMenu() {
  // 菜单基础配置
  const menuOptions = {
    type: 'none',
    name: '',
    key: '',
    url: '',
  }
  const currentEditMenu = ref({
    idx: { x: -1, n: -1 },
    menu: { type: 'none', name: '', key: '', url: '' },
  })
  // 菜单配置
  const menuConfig = ref({})
  // 获取菜单配置
  const getMenuConfig = async () => {
    try {
      const {
        data: { code, data },
      } = await fetchMenuConfig()
      menuConfig.value = initData(data)
      //   console.log(menuConfig.value)
    } catch (error) {
      console.error(error)
    }
  }
  // 删除菜单
  const delMenu = (x, n) => {
    const temp = []
    if (n) menuConfig.value[x - 1].sub_button[n - 1] = menuOptions
    else {
      for (let a = 0; a < 5; a++) temp.push(menuOptions)
      menuConfig.value[x - 1] = { ...menuOptions, sub_button: temp }
    }
  }
  // 提交菜单修改
  const submitMenu = async () => {
    const config = resolveData(menuConfig.value)
    for (let i = 0; i < config.length; i++)
      if (config[i].sub_button.length === 0) {
        ElMessage.error({
          message: '每个type为none的子菜单必须设置至少一个',
        })
        return
      }
    try {
      const {
        data: { code },
      } = await setMenu({ config })
      if (code === 2000) {
        ElMessage.success({
          message: '修改成功！',
        })
      }
    } catch (error) {
      console.error(error)
    }
  }
  // 初始化返回数据
  const initData = config => {
    for (let a = 0; a < 3; a++) {
      if (config[a]) {
        Object.keys({ ...menuOptions, sub_button: [] }).forEach(_k => {
          if (!Object.keys(config[a]).includes(_k))
            config[a][_k] = { ...menuOptions, sub_button: [] }[_k]
        })
      } else config.push({ ...menuOptions, sub_button: [] })
    }
    config.forEach(_d => {
      while (_d.sub_button.length < 5) _d.sub_button.push(menuOptions)
    })
    return config
  }
  // 反解发送数据
  const resolveData = config => {
    const data = menu => ({
      type: menu.type,
      name: menu.name,
      [menu.type === 'click' ? 'key' : 'url']: menu[
        menu.type === 'click' ? 'key' : 'url'
      ],
    })
    return config
      .filter(_d => _d.name.length)
      .map(_d => {
        if (['click', 'view'].includes(_d.type)) return data(_d)
        else
          return {
            name: _d.name,
            sub_button: _d.sub_button
              .filter(_sb => _sb.name.length)
              .map(_sb => data(_sb)),
          }
      })
  }
  onBeforeMount(() => {
    const result = []
    const temp = []
    for (let a = 0; a < 5; a++) temp.push(menuOptions)
    for (let a = 0; a < 3; a++)
      result.push({ ...menuOptions, sub_button: temp })
    menuConfig.value = result
  })
  return {
    menuConfig,
    getMenuConfig,
    submitMenu,
    currentEditMenu,
    delMenu,
  }
}
